from django.shortcuts import render
from django.http import Http404, HttpResponseRedirect
from django.db import IntegrityError
from survey.models import Question, Survey, AnswerSet
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from survey.serializer import QuestionSerializer, SurveySerializer, AnswerSetSerializer, SurveyDetailSerializer
from survey.utils import generate_qrcode, make_survey_url
from django.urls import reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
import datetime
import json
from students.models import Student


# Create your views here.
class SurveyDetail(APIView):
    def get_object(self, pk):
        try:
            return Survey.objects.get(pk=pk)
        except Survey.DoesNotExist:
            raise Http404
    
    def get(self, request, pk, format=None):
        survey = self.get_object(pk)
        question_set = Question.objects.filter(survey_id=survey.survey_id)
        serializer = SurveyDetailSerializer(survey, context={'question_set': question_set})
        return Response(serializer.data)

class SurveyViewSet(viewsets.ModelViewSet):
    queryset = Survey.objects.all().order_by('-created')
    serializer_class = SurveySerializer

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

class AnswerSetViewSet(viewsets.ModelViewSet):
    queryset = AnswerSet.objects.all()
    serializer_class = AnswerSetSerializer

    
def qrcode(request, pk):
    args = request.GET
    expired = args.get('expired')
    expired = datetime.datetime.now()
    base_url = request.build_absolute_uri('/')
    page_url = make_survey_url(base_url, pk, expired)
    
    img_stream = generate_qrcode(page_url)
    return HttpResponse(img_stream, content_type="image/jpg")

@login_required(login_url='survey_login')
def SurveyPage(request, pk):
    survey = Survey.objects.get(pk=pk)
    question_set = Question.objects.filter(survey_id=survey.survey_id)
    serializer = SurveyDetailSerializer(survey, context={'question_set': question_set})
    if request.method == "GET":
        return render(request, 'survey/survey_page.html', context=serializer.data)
    elif request.method == "POST":
        data = request.POST.lists()
        answer_set = {}
        for item in data:
            if item[0] == "csrfmiddlewaretoken":
                continue
            answer_set.update({item[0]: item[1]})
        student = Student.objects.get(pk='501810107055')
        try:
            ans = AnswerSet(survey=survey,
                        student=student,
                        answer=json.dumps(answer_set))
            ans.save()
        except IntegrityError:
            ans = AnswerSet.objects.get(survey=survey, student=student)
            ans.answer = json.dumps(answer_set)
            ans.save()
                        
        context = serializer.data
        for question in context['question_list']:
            question.update({'answers': answer_set.get(question['qid'], [])})
        return render(request, "survey/check_page.html", context)
